﻿using Gtkj.CMS.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;


namespace Gtkj.CMS.DAL
{
    public class BaseDAL<T> where T : class,new()
    {
        //syshopEntities sysET = new syshopEntities();
        DbContext sysET = DbContextFactory.CreateDbContext();
        protected    ComponentEntities entity = new ComponentEntities();


        /// <summary>
        /// 读取实体列表
        /// </summary>
        /// <param name="whereLamdba">查询条件</param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLamdba)
        {
            return sysET.Set<T>().Where(whereLamdba);
        }

        /// <summary>
        /// 读取实体分页列表
        /// </summary>
        /// <typeparam name="s">排序字段类型</typeparam>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页条数</param>
        /// <param name="totalCount">总条数</param>
        /// <param name="whereLamdba">查询条件</param>
        /// <param name="orderLamdba">排序字段</param>
        /// <param name="isAsc">true:升序,false:降序</param>
        /// <returns></returns>where( u=>u.aa==1)
        public IQueryable<T> LoadPagesEntities<s>(int pageIndex, int pageSize, out int totalCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLamdba, System.Linq.Expressions.Expression<Func<T, s>> orderLamdba, bool isAsc)
        {
            var temp = sysET.Set<T>().Where(whereLamdba);
            totalCount = temp.Count();
            if (isAsc)
            {
                temp = temp.OrderBy<T, s>(orderLamdba).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            }
            else
            {
                temp = temp.OrderByDescending<T, s>(orderLamdba).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            }
            return temp;
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool DeleteEntity(T entity)
        {
            sysET.Entry<T>(entity).State = System.Data.Entity.EntityState.Deleted;
            return true;
        }


        /// <summary>
        /// 增加实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T AddEntity(T entity)
        {
            sysET.Set<T>().Add(entity);
            return entity;
        }



        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool EditEntity(T entity)
        {
            sysET.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;
            return true;
        }
    }
}
